package 左哥算法.ch10暴力递归;

import java.util.HashMap;
import java.util.Map;

public class IdLock<T> {
    Map<T, MyLock> map = new HashMap<>();

    static class MyLock {
        int cnt;

        public MyLock(int cnt) {
            this.cnt = cnt;
        }
    }

    public synchronized Object get(T id) {
        MyLock lock = map.get(id);
        if (lock == null) {
            lock = new MyLock(0);
            map.put(id, lock);
        }
        lock.cnt++;
        return lock;
    }

    public synchronized void release(T id) {
        MyLock lock = map.get(id);
        //不存在这样的key或者其他线程使用了这个key
        if (lock == null || lock.cnt-- > 0) {
            return;
        }
        map.remove(id);
    }
}
